import {
  Badge,
  Button,
  Calendar,
  Cell,
  Dialog,
  Empty,
  Flex,
  Input,
  Loading,
  Overlay,
  Sidebar,
  Stepper,
  Tabs,
} from 'react-vant';
import './Good.css';
import GoodCard from '@/components/GoodCard';
import { useCallback, useEffect, useRef, useState } from 'react';
import GoodsApi from '@/apis/goodsApi';
import { useAppSelector } from '@/hooks/storeHooks';
import { debounceAsync, promptResult } from '@/utils/common';
import CustomOverlay from '@/components/CustomerOverlay';
import { useNavigate } from 'react-router-dom';
import PromotionsApi from '@/apis/promotionsApi';

const Good: React.FC = () => {
  const [goods, setGoods] = useState<ResponseGoodsDto[]>([]);
  const [loading, setLoading] = useState(false);
  const [loading2, setLoading2] = useState(true);
  const [pagination, setPagination] = useState({
    page: 2,
    limit: 10,
    key: '',
    total: 0,
  });
  const [hasMore, setHasMore] = useState(true);
  const [goodTypes, setGoodTypes] = useState<ResponseGoodTypeCountDto[]>([]);
  const [selectedGoodType, setSelectedGoodType] = useState(0);
  const [selectedTab, setSelectedTab] = useState(0);
  const userInfo = useAppSelector((d) => d.auth.userInfo);
  const [visible, setVisible] = useState(false);
  const [visible2, setVisible2] = useState(false);
  const [visible3, setVisible3] = useState(false);
  const [visible4, setVisible4] = useState(false);
  const [currentId, setCurrentId] = useState<number | undefined>();
  const [currentIsShelve, setCurrentIsShelve] = useState<number | undefined>();
  const [topLevel, setTopLevel] = useState(0);
  const [replenishmentCount, setReplenishmentCount] = useState(500);
  const [activeDate, setActiveDate] = useState<Date[] | undefined>();
  const [activePrice, setActivePrice] = useState<number | undefined>();
  const [activeStock, setActiveStock] = useState<number | undefined>(100);
  const goodTypesRef = useRef(goodTypes);
  const selectedGoodTypeRef = useRef(selectedGoodType);
  const navigate = useNavigate();

  useEffect(() => {
    goodTypesRef.current = goodTypes;
    selectedGoodTypeRef.current = selectedGoodType;
  }, [goodTypes, selectedGoodType]);
  // 初始化商品类型
  useEffect(() => {
    GoodsApi.getGoodTypeCount().then((res) => {
      setGoodTypes(res.data);
    });
  }, []);

  // 统一数据加载方法
  const loadData = useCallback(
    async (isAppend: boolean, page: number) => {
      const currentGoodTypes = goodTypesRef.current; // 直接读取最新值
      const currentSelectedType = selectedGoodTypeRef.current;
      const typeId = currentGoodTypes[currentSelectedType]?.gtid ?? 0;
      const status = selectedTab === 0 ? undefined : 2 - selectedTab;

      try {
        isAppend ? setLoading(true) : setLoading2(true);
        const res = await GoodsApi.getGoodsPagination(
          page,
          pagination.limit,
          pagination.key,
          userInfo.id,
          typeId,
          status
        );

        setGoods((prev) => (isAppend ? [...prev, ...res.data.data] : res.data.data));
        setPagination((prev) => ({
          ...prev,
          page: isAppend ? prev.page + 1 : 1,
          total: res.data.total,
        }));
        setHasMore(page < Math.ceil(res.data.total / pagination.limit));
      } catch (error) {
        console.error('加载失败:', error);
      } finally {
        isAppend ? setLoading(false) : setLoading2(false);
      }
    },
    [selectedTab, pagination.limit, pagination.key, userInfo.id]
  );

  // 初始化/筛选条件变化时加载
  useEffect(() => {
    if (goodTypes.length > 0) {
      loadData(false, 1);
      setPagination((prev) => {
        prev.page = 1;
        return prev;
      });
    }
  }, [goodTypes, selectedGoodType, selectedTab]);

  // 滚动加载处理
  useEffect(() => {
    const handleScroll = debounceAsync(() => {
      const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
      if (scrollHeight - (scrollTop + clientHeight) < 100 && !loading && hasMore) {
        loadData(true, pagination.page + 1);
      }
    }, 50);

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [loading, hasMore, pagination.page]);

  // 点击操作时
  const hadleOperate = (id: number, isShelve: number) => {
    setVisible(true);
    setCurrentId(id);
    setCurrentIsShelve(isShelve);
    setActivePrice(undefined);
    setActiveStock(100);
    setActiveDate(undefined);
  };

  // 上下架
  const toggoleIsShelve = () => {
    promptResult(
      GoodsApi.setGoodIsShelve(currentId as number, currentIsShelve === 0 ? 1 : 0),
      () => {},
      () => {
        let good = goods.find((d) => d.id === currentId);
        if (good) {
          good.isShelve = currentIsShelve === 0 ? 1 : 0;
        }
        setVisible(false);
      }
    );
  };

  // 设置置顶级别
  const handleSetTopLevel = () => {
    promptResult(
      GoodsApi.setGoodTopLevel(currentId as number, topLevel),
      () => {},
      () => {
        let good = goods.find((d) => d.id === currentId);
        if (good) {
          good.topLevel = topLevel;
        }
        setVisible2(false);
      }
    );
  };

  // 进货
  const handleReplenishment = () => {
    promptResult(
      GoodsApi.replenishment(currentId as number, replenishmentCount),
      () => {},
      () => {
        let good = goods.find((d) => d.id === currentId);
        if (good) {
          good.inventory += replenishmentCount;
        }
        setVisible3(false);
      }
    );
  };

  // 发布活动
  const handlePublishPromote = () => {
    if (activePrice && activeStock && activeDate) {
      promptResult(
        PromotionsApi.addPromotions({
          goodId: currentId as number,
          discountPrice: activePrice,
          startTime: new Date(activeDate[0].setHours(activeDate[0].getHours() + 8)).toISOString(),
          endTime: new Date(activeDate[1].setHours(activeDate[0].getHours() + 8)).toISOString(),
        }),
        () => {},
        () => {
          let temp = [...goods];
          temp = temp.map((d) => {
            if (d.id === currentId && activeDate[1] > new Date()) {
              d.promotePrice = activePrice;
              d.isPromote = 1;
            }
            return d;
          });
          console.log(temp);
          setGoods(temp);
          setVisible4(false);
        }
      );
    } else {
      Dialog.alert({
        message: '请选择时间、价格和库存',
      });
    }
  };

  return (
    <div>
      <div className="tabs">
        <div className="tabs-content">
          <Tabs
            active={selectedTab}
            onChange={(_, i: number) => {
              setSelectedTab(i);
            }}
          >
            <Tabs.TabPane title="全部"></Tabs.TabPane>
            <Tabs.TabPane title="已上架"></Tabs.TabPane>
            <Tabs.TabPane title="未上架"></Tabs.TabPane>
          </Tabs>
        </div>
      </div>
      <div className="main">
        <div className="sidebar">
          <div className="sidebar-content">
            <Sidebar
              value={selectedGoodType}
              onChange={(i: number) => {
                setSelectedGoodType(i);
              }}
            >
              {goodTypes.map((d) => (
                <Sidebar.Item
                  key={d.gtid}
                  title={
                    <Badge content={d.gtCount}>
                      <div style={{ minWidth: '40px' }}>{d.gtName}</div>
                    </Badge>
                  }
                />
              ))}
            </Sidebar>
          </div>
        </div>
        <div className="body">
          <div className="good-item">
            {loading2 ? (
              <div className="loading-box">
                <Loading type="spinner" color="blue" />
              </div>
            ) : goods.length === 0 ? (
              <Empty description="暂无相关商品" />
            ) : (
              <>
                <>
                  {goods.map((d) => (
                    <GoodCard
                      key={d.id}
                      data={d}
                      onOperate={hadleOperate}
                      onClick={() => navigate('detail/' + d.id)}
                    />
                  ))}
                </>
                <>
                  {loading && (
                    <div style={{ textAlign: 'center' }}>
                      <Loading className="loading-bottom">加载中...</Loading>
                    </div>
                  )}
                </>
                <>{!hasMore && <div style={{ textAlign: 'center' }}>没有更多了</div>}</>
              </>
            )}
          </div>
        </div>
      </div>
      <CustomOverlay visible={visible} onClose={() => setVisible(false)}>
        <CustomOverlay visible={visible2} onClose={() => setVisible2(false)}>
          置顶级别：
          <Stepper value={topLevel} onChange={(val) => setTopLevel(val as number)}></Stepper>
          <Flex justify="end">
            <Button type="primary" size="small" onClick={handleSetTopLevel}>
              确认
            </Button>
          </Flex>
        </CustomOverlay>
        <CustomOverlay visible={visible3} onClose={() => setVisible3(false)}>
          补货数量：
          <Stepper
            value={replenishmentCount}
            onChange={(val) => setReplenishmentCount(val as number)}
          ></Stepper>
          <Flex justify="end">
            <Button type="primary" size="small" onClick={handleReplenishment}>
              确认
            </Button>
          </Flex>
        </CustomOverlay>
        <CustomOverlay visible={visible4} onClose={() => setVisible4(false)}>
          <div style={{ display: 'flex', margin: '8px' }}>
            <div>活动价格：</div>
            <Input
              style={{ flex: 1 }}
              type="number"
              value={activePrice as any}
              placeholder="请输入"
              onChange={(val) => setActivePrice(parseFloat(val))}
            ></Input>
          </div>
          <div style={{ margin: '8px' }}>
            活动库存：
            <Stepper
              value={activeStock}
              onChange={(val) => setActiveStock(val as number)}
            ></Stepper>
          </div>
          <div style={{ margin: '8px' }}>
            <Calendar
              type="range"
              allowSameDay
              value={activeDate}
              onConfirm={(val: any) => setActiveDate(val)}
            >
              {(val: any, actions) => (
                <div onClick={() => actions.open()}>
                  日期区间：
                  {val ? val.map((el: any) => el.toLocaleDateString()).join('~') : '请选择日期'}
                </div>
              )}
            </Calendar>
          </div>
          <Flex justify="end">
            <Button type="primary" size="small" onClick={handlePublishPromote}>
              确认
            </Button>
          </Flex>
        </CustomOverlay>
        <div>
          <Button size="large" type="danger" onClick={() => setVisible2(true)}>
            置顶
          </Button>

          {currentIsShelve ? (
            <Button
              size="large"
              // @ts-ignore
              type="success"
              style={{ background: '#ccc', borderColor: 'white' }}
              onClick={toggoleIsShelve}
            >
              下架
            </Button>
          ) : (
            // @ts-ignore
            <Button size="large" type="success" onClick={toggoleIsShelve}>
              上架
            </Button>
          )}

          <Button
            size="large"
            type="warning"
            style={{ background: '#faad14', borderColor: '#faad14' }}
            onClick={() => setVisible3(true)}
          >
            补货
          </Button>

          <Button size="large" type="primary" onClick={() => setVisible4(true)}>
            活动
          </Button>
        </div>
      </CustomOverlay>
    </div>
  );
};

export default Good;
